import React, { useEffect, useState } from 'react'
import PageHeader from './components/page-header'
import PageMain from './components/page-main'
import * as server from '../../services/todo'
import './index.less'

const useOperationList = (initValue) => {
  const [list, setList] = useState(initValue)
  const [dataLoading, setDataLoading] = useState(false)

  const query = () => {
    setDataLoading(true)
    server.queryList().then(res => {
      if (res.data) {
        setList(res.data.reverse())
      }
      setDataLoading(false)
    })
  }

  useEffect(query, [])

  const addList = (item) => {
    server.addList(item).then(res => {
      if (res.code === 200) {
        query()
      }
    })
  }

  const completeList = (item) => {
    server.completeList(item).then(res => {
      if (res.code === 200) {
        query()
      }
    })
  }

  const removeList = (item) => {
    server.removeList(item).then(res => {
      if (res.code === 200) {
        query()
      }
    })
  }
  return { list, addList, completeList, removeList, dataLoading }
}

function Page() {
  const { list, addList, completeList, removeList, dataLoading } = useOperationList([])

  const headerProps = {
    handleOk(item) {
      item.key = Date.now()
      item.complete = false
      addList(item)
    }
  }

  const mainProps = {
    data: list,
    loading: dataLoading,
    onTodoComplete: completeList,
    onTodoDelete: removeList
  }

  return (
    <div className="todos">
      <PageHeader {...headerProps} />
      <PageMain {...mainProps} />
    </div>
  )
}

export default Page
